<template>
  <mars-dialog v-bind="attrs" :title="formState.name" handles="y" width="330" top="300" :right="10">
    <div class="fly-pannel_view">
      <div class="f-pt">
        <a-space>
          <span class="mars-pannel-item-label">漫游速度:</span>
          <mars-input-number
            :min="0"
            :max="99999"
            v-model:value="formState.multiplier"
            :step="0.1"
            @change="updateMultiplier"></mars-input-number>
        </a-space>
      </div>

      <div>
        <a-space>
          <span class="mars-pannel-item-label">视角模式:</span>
          <mars-select v-model:value="formState.cameraType" :options="perspectiveMode"
            @select="viewChane"></mars-select>
        </a-space>
      </div>
      <div class="f-pt" v-show="distanceIsShow">
        <a-space>
          <span class="mars-pannel-item-label">视角距离:</span>
          <mars-input-number
            :min="0"
            :max="99999"
            v-model:value="formState.followedX"
            :step="0.1"
            @change="updateCameraSetting"></mars-input-number>
        </a-space>
      </div>
      <div class="f-pt" v-show="isShow">
        <a-space>
          <span class="mars-pannel-item-label">视角高度:</span>
          <mars-input-number
            :min="0"
            :max="99999"
            v-model:value="formState.followedZ"
            :step="0.1"
            @change="updateCameraSetting"></mars-input-number>
        </a-space>
      </div>
      <div class="f-pt" v-show="otherIsShow">
        <a-space>
          <span class="mars-pannel-item-label">高度偏移值:</span>
          <mars-input-number
            :min="0"
            :max="99999"
            v-model:value="formState.offsetZ"
            :step="0.1"
            @change="updateCameraSetting"></mars-input-number>
        </a-space>
      </div>

      <div class="f-pt" v-show="otherIsShow">
        <a-space>
          <span class="mars-pannel-item-label">横向偏移值:</span>
          <mars-input-number
            :min="0"
            :max="99999"
            v-model:value="formState.offsetX"
            :step="0.1"
            @change="updateCameraSetting"></mars-input-number>
        </a-space>
      </div>

      <div class="f-pt" v-show="otherIsShow">
        <a-space>
          <span class="mars-pannel-item-label">前后偏移值:</span>
          <mars-input-number
            :min="0"
            :max="99999"
            v-model:value="formState.offsetY"
            :step="0.1"
            @change="updateCameraSetting"></mars-input-number>
        </a-space>
      </div>

      <div class="f-mb f-tac f-pt">
        <a-space>
          <mars-button class="stop-play" :disabled="btnDisabled" @click="onClickStop">
            <template #icon>
              <mars-icon icon="pause-one" width="20"></mars-icon>
            </template>
            停止漫游
          </mars-button>
          <mars-button :disabled="btnDisabled" @click="showHeightChars">
            <template #icon>
              <mars-icon icon="chart-line" width="20"></mars-icon>
            </template>
            查看剖面图</mars-button>
        </a-space>
      </div>
    </div>

    <div class="fly-pannel_params">
      <div class="percent">
        <a-progress :percent="formState.percent" size="small" color="#fff" />
      </div>

      <div class="already">
        <a-space>
          <div class="already-length">
            <p class="mars-text">{{ formState.td_length }}</p>
            <p>已漫游长度</p>
          </div>

          <div class="already-time">
            <p class="mars-text">{{ formState.td_times }}</p>
            <p>已漫游时间</p>
          </div>
        </a-space>
      </div>

      <div class="postions">
        <a-space>
          <div class="postions-lng">
            <p class="mars-text">{{ formState.td_jd }}</p>
            <p>经度</p>
          </div>

          <div class="postions-lat">
            <p class="mars-text">{{ formState.td_wd }}</p>
            <p>纬度</p>
          </div>

          <div class="postions-alt">
            <p class="mars-text">{{ formState.td_gd }}</p>
            <p>漫游高程</p>
          </div>
        </a-space>
      </div>

      <div class="all">
        <div class="all-length">
          <p class="mars-text">{{ formState.td_alllength }}</p>
          <p>总长度</p>
        </div>
        <div class="all-time">
          <p class="mars-text">{{ formState.td_alltimes }}</p>
          <p>总时长</p>
        </div>
      </div>
    </div>
  </mars-dialog>

  <mars-dialog :draggable="false" left="10" right="10" v-model:visible="isShowCharts" :before-close="closeEchats"
    closeable top="60">
    <div class="ech">
      <div id="echarts-view" class="echartsView"></div>
    </div>
  </mars-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, toRaw, UnwrapRef, ref, useAttrs, onUnmounted } from "vue"
import * as mapWork from "../roamLine/map"
import useLifecycle from "@mars/common/uses/use-lifecycle"
import * as echarts from "echarts"
import { useWidget } from "@mars/common/store/widget"

const { activate, currentWidget, updateWidget } = useWidget()
// 启用map.ts生命周期
useLifecycle(mapWork)

const attrs = useAttrs()

interface FormState {
  cameraType: string
  name: string
  td_alllength: string | number
  td_length: string | number
  td_alltimes: string | number
  td_times: string | number
  td_jd: number
  td_wd: number
  td_gd: string | number
  td_dmhb: number
  td_ldgd: number
  percent: number
  followedX: number
  followedZ: number
  offsetZ: number
  offsetX: number
  offsetY: number
  multiplier: number
}

const formState: UnwrapRef<FormState> = reactive({
  cameraType: "",
  name: "",
  td_alllength: 0,
  td_length: 0,
  td_alltimes: 0,
  td_times: 0,
  td_jd: 0,
  td_wd: 0,
  td_gd: 0,
  td_dmhb: 0,
  td_ldgd: 0,
  percent: 0,
  followedX: 50,
  followedZ: 10,
  offsetZ: 0,
  offsetX: 0,
  offsetY: 0,
  multiplier: 0
})

const isShow = ref(false) // 视角距离显示
const otherIsShow = ref(false)
const isShowCharts = ref(false)
const btnDisabled = ref(true)
const perspectiveMode = [
  {
    value: "",
    label: "无"
  },
  {
    value: "gs",
    label: "跟随视角"
  },
  {
    value: "dy",
    label: "锁定第一视角"
  },
  {
    value: "sd",
    label: "锁定上帝视角"
  }
]

onMounted(() => {
  const graphicOptions = currentWidget.data?.graphicOptions
  formState.multiplier = mapWork.getRoamLineData(toRaw(graphicOptions))

  initRoamlineOptions(graphicOptions)
  updateWidget("toolbar", { enter: true, name: "roamLine-list" })
})

onUnmounted(() => {
  window.removeEventListener("onresize", winEvent)
  if (myChart) {
    myChart.dispose()
  }

  updateWidget("toolbar", "roamLine")
})
let winEvent: any

// 剖面图数据
let myChart: echarts.ECharts
let echartData: any

// 数据更新
mapWork.eventTarget.on("roamLineChange", (event: any) => {
  roamLineChange(event)
  if (isShowCharts.value) {
    updateFlyOk(event.distance)
  }
})

function initRoamlineOptions(options) {
  formState.name = options.name

  formState.cameraType = options.camera?.type
  isShowInput(options.camera?.type)
  formState.followedX = formState.cameraType === "gs" ? options.camera?.radius : options.camera?.followedX
  formState.followedZ = options.camera?.followedZ
  formState.offsetZ = options.camera?.offsetZ
  btnDisabled.value = false

}

// 变化的数据
function roamLineChange(item: any) {
  let val = Math.ceil((item.distance * 100) / item.distance_all)
  if (val < 1) {
    val = 0
  }
  if (val > 100) {
    val = 100
  }
  formState.percent = val

  formState.td_length = mapWork.formatDistance(item.distance) || "0米"
  formState.td_times = mapWork.formatTime(item.second)
  formState.td_jd = item.point?.lng
  formState.td_wd = item.point?.lat
  formState.td_gd = mapWork.formatDistance(item.point?.alt)

  formState.td_alllength = mapWork.formatDistance(item.distance_all)
  formState.td_alltimes = mapWork.formatTime(item.second_all)
}

function updateFlyOk(len: number) {
  if (!echartData || isNaN(len)) {
    return
  }
  const arrFlyOk = [] // 已漫游
  for (let i = 0; i < echartData.arrFxgd.length; i++) {
    if (echartData.arrLength[i] <= len) {
      arrFlyOk.push(echartData.arrFxgd[i])
    } else {
      break
    }
  }

  // 填入数据,根据名字对应到相应的系列
  myChart.setOption({
    series: [{ name: "已漫游", data: arrFlyOk, zlevel: 100, areaStyle: "color: rab(235, 204, 88)" }]
  })
}

// 视角发生改变
const distanceIsShow = ref(true)
const viewChane = (value: string) => {
  updateCameraSetting()
  isShowInput(value)
}

function isShowInput(cameraType: string) {
  if (cameraType === "") {
    distanceIsShow.value = false
    isShow.value = false
    otherIsShow.value = false
  }

  if (cameraType === "sd") {
    distanceIsShow.value = false
    isShow.value = true
    otherIsShow.value = false
  }
  if (cameraType === "gs") {
    distanceIsShow.value = true
    isShow.value = false
    otherIsShow.value = false
  }

  if (cameraType === "dy") {
    otherIsShow.value = true
  }
}

// 改变视角模式
function updateCameraSetting() {
  mapWork.setCameraOptions({
    type: formState.cameraType,
    radius: formState.cameraType === "gs" ? formState.followedX : 0,
    followedX: formState.followedX,
    followedZ: formState.followedZ,
    offsetZ: formState.offsetZ,
    offsetY: formState.offsetY,
    offsetX: formState.offsetX
  })
}

function updateMultiplier(num: number) {
  mapWork.updateMultiplier(num)
}

// 停止漫游
const onClickStop = () => {
  activate("roamLine-list")
  mapWork.stopRoamLine()
  isShowCharts.value = false
}

// ===============echarts图表部分======================

// 飞行漫游 图表
function setEchartsData() {
  if (echartData == null || myChart == null) {
    return
  }

  const option: any = {
    animation: false,
    legend: {
      data: ["地面海拔", "漫游海拔", "已漫游"]
    },
    grid: {
      left: 10,
      right: 10,
      bottom: 10,
      containLabel: true
    },
    dataZoom: [
      {
        type: "inside",
        throttle: 50
      }
    ],
    tooltip: {
      trigger: "axis",
      // position: function (point, params, dom, rect, size) {
      //    return [10, 20];
      // },
      formatter: function (params: any) {
        let inhtml = ""
        if (params.length < 2) {
          return inhtml
        }

        const hbgd = params[0].value // 海拔高度
        const fxgd = params[1].value // 漫游海拔

        const point = echartData.arrPoint[params[0].dataIndex] // 所在经纬度

        inhtml +=
          "所在位置&nbsp;" +
          point.lng +
          "," +
          point.lat +
          "<br />" +
          params[1].seriesName +
          "&nbsp;<label style='color:" +
          params[1].color +
          ";'>" +
          params[1].value +
          "</label>&nbsp;米<br />"

        if (hbgd !== 0) {
          inhtml += params[0].seriesName + "&nbsp;<label style='color:" + params[0].color + ";'>" + params[0].value + "</label>&nbsp;米<br />"
          const ldgd = fxgd - hbgd // 离地高度
          inhtml += "距离地面&nbsp;<label style='color:" + params[1].color + ";'>" + ldgd.toFixed(1) + "</label>&nbsp;米"
          // if (charsData.arrBjgd) {
          //     var bjgd = charsData.arrBjgd[params[0].dataIndex];
          //     if (bjgd > fxgd)
          //         inhtml += "(低于报警<label style='color:red;'>&nbsp;" + (bjgd - ldgd).toFixed(1) + "</label>&nbsp;米)";
          // }
        }

        return inhtml
      }
    },
    xAxis: [
      {
        name: "行程",
        type: "category",
        boundaryGap: false,
        axisLine: {
          show: false
        },
        axisLabel: {
          show: false
        },
        data: echartData.arrLength
      }
    ],
    yAxis: [
      {
        // name: '高度',
        type: "value",
        axisLabel: {
          fontSize: "10",
          formatter: "{value} 米"
        }
      }
    ],
    series: [
      {
        name: "地面海拔",
        type: "line",
        smooth: true,
        symbol: "none",
        sampling: "average",
        itemStyle: {
          normal: {
            color: "rgb(255, 70, 131)"
          }
        },
        areaStyle: {
          normal: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: "rgb(255, 158, 68)"
              },
              {
                offset: 1,
                color: "rgb(255, 70, 131)"
              }
            ])
          }
        },
        data: echartData.arrHbgd
      },
      {
        name: "漫游海拔",
        type: "line",
        smooth: false,
        symbol: "none",
        data: echartData.arrFxgd
      },
      {
        name: "已漫游",
        type: "line",
        data: []
      }
    ]
  }

  winEvent = window.onresize = () => {
    myChart.resize()
  }
  myChart.setOption(option)
  myChart.resize()
}

// 显示剖面图
const showHeightChars = async () => {
  isShowCharts.value = true
  const data = await mapWork.getTerrainHeight()
  echartData = data
  myChart = echarts.init(document.getElementById("echarts-view")!, "dark")
  setEchartsData()
}

// 关闭剖面图
const closeEchats = () => {
  if (myChart) {
    myChart.clear()
  }
}
</script>

<style scoped lang="less">
.ant-select,
.ant-input-number {
  width: 216px;
}

.ech {
  height: 200px;
  width: 100%;
}

.ech .echartsView {
  width: 100%;
  height: 100%;
}

:deep(.ant-progress) {
  .ant-progress-outer {
    .ant-progress-inner {
      background-color: rgba(231, 231, 231, 0.15) !important;
    }
  }

  .ant-progress-text {
    color: #fff;
  }
}

:deep(.ant-progress-text) {
  color: #fff !important;
}

.percent {
  width: 300px;
  height: 30px;
  line-height: 30px;
  border-radius: 2px;
  background: rgba(255, 255, 255, 0.2);

  .ant-progress {
    width: 274px;
    margin-left: 10px;
  }
}

.already {
  margin-top: 10px;
  width: 300px;

  .already-length,
  .already-time {
    width: 146px;
    height: 60px;
    border-radius: 2px;
    background: rgba(255, 255, 255, 0.2);
    text-align: center;
  }
}

.postions {
  margin-top: 10px;
  width: 300px;

  .postions-lng,
  .postions-lat,
  .postions-alt {
    width: 95px;
    height: 60px;
    border-radius: 2px;
    background: rgba(255, 255, 255, 0.2);
    text-align: center;
  }
}

.all {
  display: flex;
  justify-content: space-around;
  height: 60px;
  width: 300px;
  margin-top: 10px;
  border-radius: 2px;
  background: rgba(255, 255, 255, 0.2);
}

.mars-text {
  display: inline-block;
  margin-top: 10px;
}

.mars-button {
  width: 144px;
}

.stop-play {
  background: #2cc719;
}

.mars-pannel-item-label {
  min-width: 73px;
}
</style>
